<template>
	<div class="page">
		<el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
		            <!-- 搜索框-->
		         <el-form-item prop="associatedType">
		                  <el-select v-model="searchForm.associatedType" placeholder="请选择关联类型" size="small" style="width: 100%;">
		                    <el-option
		                      v-for="item in $dictUtils.getDictList('zhaohang_contract_type')"
		                      :key="item.value"
		                      :label="item.label"
		                      :value="item.value">
		                    </el-option>
		                  </el-select>
		         </el-form-item>
		         <el-form-item prop="sysuser.id">
		            <user-select :limit='1' size="small" placeholder="请选择收集人" :value="searchForm.sysuser.id" @getValue='(value) => {searchForm.sysuser.id=value}'></user-select>
		         </el-form-item>
		         <el-form-item prop="type">
		                  <el-select v-model="searchForm.type" placeholder="请选择发票类型" size="small" style="width: 100%;">
		                    <el-option
		                      v-for="item in $dictUtils.getDictList('invoicebill_type')"
		                      :key="item.value"
		                      :label="item.label"
		                      :value="item.value">
		                    </el-option>
		                  </el-select>
		         </el-form-item>
		         <el-form-item prop="subType">
		                  <el-select v-model="searchForm.subType" placeholder="请选择细分发票类型" size="small" style="width: 100%;">
		                    <el-option
		                      v-for="item in $dictUtils.getDictList('sub_bill_type')"
		                      :key="item.value"
		                      :label="item.label"
		                      :value="item.value">
		                    </el-option>
		                  </el-select>
		         </el-form-item>
		         <el-form-item prop="invoiceCode"> 
		                <el-input size="small" v-model="searchForm.invoiceCode" placeholder="发票代码" clearable></el-input>
		         </el-form-item>
		         <el-form-item prop="invoiceNo">
		                <el-input size="small" v-model="searchForm.invoiceNo" placeholder="发票号码" clearable></el-input>
		         </el-form-item>
		         <el-form-item prop="invoiceDate">
		                <el-input size="small" v-model="searchForm.invoiceDate" placeholder="开票日期" clearable></el-input>
		         </el-form-item>
		         <el-form-item prop="payerName">
		                <el-input size="small" v-model="searchForm.payerName" placeholder="购方姓名" clearable></el-input>
		         </el-form-item>
		         <el-form-item prop="sellerName">
		                <el-input size="small" v-model="searchForm.sellerName" placeholder="销方姓名" clearable></el-input>
		         </el-form-item>
		          <el-form-item>
		            <el-button type="primary" @click="refreshList()" size="small">查询</el-button>
		            <el-button @click="resetSearch()" size="small">重置</el-button>
		          </el-form-item>
		      </el-form>
		<!-- 导入导出-->
		<el-dialog title="导入Excel" :visible.sync="isImportCollapse">
			<el-form size="small" :inline="true" v-show="isImportCollapse" ref="importForm">
				<el-form-item>
					<el-button type="default" @click="downloadTpl()" size="small">下载模板</el-button>
				</el-form-item>
				<el-form-item prop="loginName">
					<el-upload class="upload-demo"
						:action="`${this.$http.BASE_URL}/zhaohang/invoice/web/companyticket/sysCompanyTicket/import`"
						:on-success="uploadSuccess" :show-file-list="true">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只允许导入“xls”或“xlsx”格式文件！</div>
					</el-upload>
				</el-form-item>
			</el-form>
		</el-dialog>
		<el-dialog title="新增发票" :visible.sync="addInvoiceDlalog" width="50%">
			<el-form :model="addInvoiceForm" size="small" label-width="140px" ref="addInvoiceForms"
				v-loading="addInvoiceFormLoading">
				<el-row :gutter="15">
					<el-col :span="12">
						<el-form-item label="发票类型" prop="makeInvoice"
							:rules="[{required: true, message:'发票类型不能为空', trigger:'blur'}]">
							<el-select v-model="addInvoiceForm.makeInvoice" placeholder="请选择" style="width: 100%;">
								<el-option v-for="item in $dictUtils.getDictList('zh_make_invoice')" :key="item.value"
									:label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="附件" prop="image"
							:rules="[{required: true, message:'附件不能为空', trigger:'blur'}]">
							<!-- :on-preview="(file, fileList) => {$window.location.href = (file.response && file.response.url) || file.url}"   :on-preview="(file) => {document.location.href = file.url}"-->
							<el-upload ref="image" :action="`${this.$http.BASE_URL}/zh/test/uploadInvoice`"
								:headers="{token: $cookie.get('token')}"
								:on-preview="(file) => {$window.open ((file.response && file.response.url) || file.url,'_blank') }"
								:on-success="(response, file, fileList) => {
						           addInvoiceForm.image = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
						        }" :on-remove="(file, fileList) => {
						          $http.post(`/dlyrlTest/deleteFile?path=${(file.response && file.response.url) || file.url}`).then(({data}) => {
						            $message.success(data.msg)
						          })
						          addInvoiceForm.image = fileList.map(item => item.url).join('|')
						        }" :before-remove="(file, fileList) => {
						          return $confirm(`确定移除 ${file.name}？`)
						        }" multiple :limit="1" :on-exceed="(files, fileList) =>{
						          $message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
						        }" :file-list="imageArray">
								<el-button size="small" type="primary">点击上传</el-button>
								<div slot="tip" class="el-upload__tip">添加相关附件</div>
							</el-upload>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button size="small" type="primary" @click="closeAddInvoiceFormOne" plain>关闭</el-button>
				<el-button size="small" type="primary" @click="addInvoiceFormOne" plain>确定</el-button>
			</span>
		</el-dialog>
		<div class="bg-white top">
			<el-row>
				<!-- <el-button v-if="hasPermission('zhaohang:invoice:web:companyticket:sysCompanyTicket:add')"
					type="primary" size="small" icon="el-icon-plus" @click="add()">新建</el-button>
				<el-button v-if="hasPermission('zhaohang:invoice:web:companyticket:sysCompanyTicket:edit')"
					type="warning" size="small" icon="el-icon-edit-outline" @click="edit()"
					:disabled="dataListSelections.length != 1" plain>修改</el-button>
				<el-button v-if="hasPermission('zhaohang:invoice:web:companyticket:sysCompanyTicket:del')" type="danger"
					size="small" icon="el-icon-delete" @click="del()" :disabled="dataListSelections.length <= 0" plain>
					删除
				</el-button> -->
				<el-button type="primary" size="small" plain @click="addInvoiceDlalog=true">新增发票</el-button>
				<el-button  type="danger"   size="small" icon="el-icon-delete" @click="del()" :disabled="dataListSelections.length <= 0" plain>删除</el-button>
				<el-button-group class="pull-right">
					<el-button v-if="hasPermission('zhaohang:invoice:web:companyticket:sysCompanyTicket:import')"
						type="default" size="small" icon="el-icon-upload2" title="导入"
						@click="isImportCollapse = !isImportCollapse"></el-button>
					<el-button v-if="hasPermission('zhaohang:invoice:web:companyticket:sysCompanyTicket:export')"
						type="default" size="small" icon="el-icon-download" title="导出" @click="exportExcel()">
					</el-button>
					<el-button type="default" size="small" icon="el-icon-refresh" @click="refreshList">
					</el-button>
				</el-button-group>
			</el-row>
			<el-tabs v-model="activeName" @tab-click="handleClick" type="border-card" class="table">
			    <el-tab-pane v-for = "item, index in onInvoices" :key="index" :label="item.text" :name="item.name" >
					<el-table :data="dataList" size="small" height="350px" @selection-change="selectionChangeHandle"
						@sort-change="sortChangeHandle" v-loading="loading"  :cell-style="cellStyle"
						style="border:1px solid #d6cfe2;" :header-cell-class-name="cellHeadStyle"
						:row-class-name="tableRowClassName">
						<el-table-column type="selection" header-align="center" align="center" width="50">
						</el-table-column>
						<el-table-column prop="company.name" show-overflow-tooltip label="公司">
							<template slot-scope="scope">
								<el-link type="primary" :underline="false" @click="view(scope.row.id)">
									{{scope.row.company.name}}</el-link>
							</template>
						</el-table-column>
						<!-- <el-table-column prop="imageID" show-overflow-tooltip label="发票id">
						</el-table-column> -->
						<!-- <el-table-column prop="oldUrl" show-overflow-tooltip label="发票原件">
						</el-table-column> -->
						<!-- <el-table-column prop="isassociated" show-overflow-tooltip label="是否关联">
							<template slot-scope="scope">
								{{ $dictUtils.getDictLabel("is_associated", scope.row.isassociated, '-') }}
							</template>
						</el-table-column>
						<el-table-column prop="associatedType" show-overflow-tooltip label="关联类型">
							<template slot-scope="scope">
								{{ $dictUtils.getDictLabel("zhaohang_contract_type", scope.row.associatedType, '-') }}
							</template>
						</el-table-column>
						<el-table-column prop="foreignId" show-overflow-tooltip label="关联外键">
						</el-table-column> -->
						<el-table-column prop="makeInvoice" show-overflow-tooltip label="开票方">
						</el-table-column>
						<el-table-column prop="sysuser.name" show-overflow-tooltip label="收集人">
						</el-table-column>
						<!-- <el-table-column prop="dmzUrl" show-overflow-tooltip label="发票图片">
						</el-table-column> -->
						<el-table-column prop="type" show-overflow-tooltip label="发票类型">
							<template slot-scope="scope">
								{{ $dictUtils.getDictLabel("invoicebill_type", scope.row.type, '-') }}
							</template>
						</el-table-column>
						<el-table-column prop="subType" show-overflow-tooltip label="细分发票类型" width="120">
							<template slot-scope="scope">
								{{ $dictUtils.getDictLabel("sub_bill_type", scope.row.subType, '-') }}
							</template>
						</el-table-column>
						<el-table-column prop="invoiceCode" show-overflow-tooltip label="发票代码">
						</el-table-column>
						<el-table-column prop="invoiceNo" show-overflow-tooltip label="发票号码">
						</el-table-column>
						<el-table-column prop="invoiceDate" show-overflow-tooltip label="开票日期">
						</el-table-column>
						<el-table-column prop="noTaxAmount" show-overflow-tooltip label="金额">
						</el-table-column>
						<el-table-column prop="checkCode" show-overflow-tooltip label="校验码">
						</el-table-column>
						<el-table-column prop="withTaxAmount" show-overflow-tooltip label="含税价格">
						</el-table-column>
						<el-table-column prop="payerTaxNo" show-overflow-tooltip label="购方税号">
						</el-table-column>
						<el-table-column prop="payerName" show-overflow-tooltip label="购方姓名">
						</el-table-column>
						<el-table-column prop="sellerTaxNo" show-overflow-tooltip label="销方税号">
						</el-table-column>
						<el-table-column prop="sellerName" show-overflow-tooltip label="销方姓名">
						</el-table-column>
						<el-table-column header-align="center" align="center" fixed="right" :key="Math.random()" width="200"
							label="点击查看">
							<template slot-scope="scope">
								<el-image style="width: 100px; height: 50px" :src="scope.row.dmzUrl"
									:preview-src-list="[scope.row.dmzUrl]"></el-image>
								<!-- <el-button v-if="hasPermission('zhaohang:invoice:web:companyticket:sysCompanyTicket:view')"
									type="text" icon="el-icon-view" size="small" @click="view(scope.row.id)">查看</el-button>
								<el-button v-if="hasPermission('zhaohang:invoice:web:companyticket:sysCompanyTicket:edit')"
									type="text" icon="el-icon-edit" size="small" @click="edit(scope.row.id)">修改</el-button>
								<el-button v-if="hasPermission('zhaohang:invoice:web:companyticket:sysCompanyTicket:del')"
									type="text" icon="el-icon-delete" size="small" @click="del(scope.row.id)">删除</el-button> -->
							</template>
						</el-table-column>
					</el-table>
					<el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageNo"
						:page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" background
						layout="total, sizes, prev, pager, next, jumper">
					</el-pagination>
				</el-tab-pane>
			</el-tabs>
			
		</div>
		<!-- 弹窗, 新增 / 修改 -->
		<SysCompanyTicketForm ref="sysCompanyTicketForm" @refreshDataList="refreshList"></SysCompanyTicketForm>
	</div>
</template>

<script>
	import tableStyles from '../../../../../../utils/mixins.js'
	import SysCompanyTicketForm from './SysCompanyTicketForm'
	import UserSelect from '@/components/userSelect'
	export default {
		mixins: [tableStyles],
		data() {
			return {
				searchForm: {
					associatedType: '',
					type: '',
					subType: '',
					invoiceCode: '',
					invoiceNo: '',
					invoiceDate: '',
					payerName: '',
					sellerName: '',
					sysuser: {
						id: ''
					},
				},
				dataList: [],
				pageNo: 1,
				pageSize: 10,
				total: 0,
				orderBy: '',
				dataListSelections: [],
				isImportCollapse: false,
				loading: false,
				//新增发票
				addInvoiceDlalog: false,
				addInvoiceFormLoading: false,
				imageArray: [],
				addInvoiceForm: {
					image: "",
					makeInvoice:"",
				},
				// 查看大图
				showViewer: false,
				imgList: [],
				
				activeName:"A",
				onInvoices:[{
					text: "收款发票",
					name: "A"
				  }, {
					text: "付款发票",
					name: "B"
				  }]
			}
		},
		components: {
			UserSelect,
			SysCompanyTicketForm
		},
		activated() {
			this.refreshList()
		},
		methods: {
			handleClick(val){
				console.log(val)
				this.activeName=val.name;
				this.refreshList();
			},
			ImageView(obj) {
				console.log(obj);
				this.imgList.push(obj.dmzUrl);
				this.showViewer = true;
			},
			addInvoiceFormOne() {
				this.$refs['addInvoiceForms'].validate((valid) => {
					if (valid) {
						this.addInvoiceFormLoading = true;
						this.$http({
							url: '/zhaohang/invoice/web/companyticket/sysCompanyTicket/saveCompanyInvoice',
							method: 'post',
							params: {
								company: this.$store.state.user.companyId,
								...this.addInvoiceForm
							}
						}).then(({
							data
						}) => {
							if (data) {
								this.addInvoiceFormLoading = false;
								if (data.success) {
									this.closeAddInvoiceFormOne();
									this.refreshList();
									this.$message.success(data.msg);
								}
							}
						})
					}
				})
			},
			closeAddInvoiceFormOne() {
				this.addInvoiceDlalog = false;
				this.$refs.addInvoiceForms.resetFields();
				this.imageArray = [];
				this.addInvoiceForm.image = "";
			},
			// 获取数据列表
			refreshList() {
				this.loading = true
				this.$http({
					url: '/zhaohang/invoice/web/companyticket/sysCompanyTicket/list',
					method: 'get',
					params: {
						'pageNo': this.pageNo,
						'pageSize': this.pageSize,
						'orderBy': this.orderBy,
						'company': this.$store.state.user.companyId,
						'makeInvoice': this.activeName,
						...this.searchForm
					}
				}).then(({
					data
				}) => {
					if (data && data.success) {
						this.dataList = data.page.list
						this.total = data.page.count
						this.loading = false
					}
				})
			},
			// 每页数
			sizeChangeHandle(val) {
				this.pageSize = val
				this.pageNo = 1
				this.refreshList()
			},
			// 当前页
			currentChangeHandle(val) {
				this.pageNo = val
				this.refreshList()
			},
			// 多选
			selectionChangeHandle(val) {
				this.dataListSelections = val
			},

			// 排序
			sortChangeHandle(obj) {
				if (obj.order === 'ascending') {
					this.orderBy = obj.prop + ' asc'
				} else if (obj.order === 'descending') {
					this.orderBy = obj.prop + ' desc'
				} else {
					this.orderBy = ''
				}
				this.refreshList()
			},
			// 新增
			add() {
				this.$refs.sysCompanyTicketForm.init('add', '')
			},
			// 修改
			edit(id) {
				id = id || this.dataListSelections.map(item => {
					return item.id
				})[0]
				this.$refs.sysCompanyTicketForm.init('edit', id)
			},
			// 查看
			view(id) {
				this.$refs.sysCompanyTicketForm.init('view', id)
			},
			// 删除
			del(id) {
				let ids = id || this.dataListSelections.map(item => {
					return item.id
				}).join(',')
				this.$confirm(`确定删除所选项吗?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.loading = true
					this.$http({
						url: '/zhaohang/invoice/web/companyticket/sysCompanyTicket/delete',
						method: 'delete',
						params: {
							'ids': ids
						}
					}).then(({
						data
					}) => {
						if (data && data.success) {
							this.$message.success(data.msg)
							this.refreshList()
						}
						this.loading = false
					})
				})
			},
			// 导入成功
			uploadSuccess(res, file) {
				if (res.success) {
					this.$message.success({
						dangerouslyUseHTMLString: true,
						message: res.msg
					})
				} else {
					this.$message.error(res.msg)
				}
			},
			// 下载模板
			downloadTpl() {
				this.$utils.download('/zhaohang/invoice/web/companyticket/sysCompanyTicket/import/template')
			},
			exportExcel() {
				let params = {
					...this.searchForm
				}
				this.$utils.download('/zhaohang/invoice/web/companyticket/sysCompanyTicket/export', params)
			},
			resetSearch () {
				this.$refs.searchForm.resetFields()
				this.refreshList()
			  }
		}
	}
</script>
